#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <getopt.h>
#include "CPHMediaEngine.h"

using namespace std;

#define WIDTH 720
#define HEIGHT 1280

namespace {
	CPHMediaEngine mediaEngine;
}

int InjectKey_api(int key)
{
	InputKey inputKey;
	inputKey.action = 0;
	inputKey.keyCode = static_cast<uint16_t>(key);
	int iRet = mediaEngine.InjectKeyData(inputKey);
	if (iRet != 0) {
		std::cout << "inject key failed" << std::endl;
		return -1;
	}
	inputKey.action = 1;
	usleep(100000);
	iRet = mediaEngine.InjectKeyData(inputKey);
	if (iRet != 0) {
		std::cout << "inject key failed" << std::endl;
		return -1;
	}
	std::cout << "InjectKey_api success" << std::endl;
	return 0;
}

int InjectTouch_api(int x, int y)
{
	InputTouch touch;
	touch.pointerID = 0;
	touch.orientation = 0;
	touch.action = 0;
	touch.pressure = 1;
	touch.touchX = static_cast<uint16_t>(x);
	touch.touchY = static_cast<uint16_t>(y);
	touch.physicalWidth = WIDTH;
	touch.physicalHeight = HEIGHT;
	touch.touchTime = 0;
	int iRet = mediaEngine.InjectTouchData(touch);
	if (iRet != 0) {
		std::cout << "api inject down failed" << std::endl;
		return -1;
	}
	touch.touchTime = 10;
	touch.action = 1;
	iRet = mediaEngine.InjectTouchData(touch);
	if (iRet != 0) {
		std::cout << "api inject down failed" << std::endl;
		return -1;
	}
	std::cout << "api inject touch time success" << std::endl;
	return 0;
}

enum TestOpt {
	OPT_TOUCH,
	OPT_KEY,
	OPT_MAX
};

void PrintHelp()
{
	std::cout << "input as -->> testTouch -t 0:touch 1:key -k 3 -x 100 -y 100" << std::endl;
}

int main(int argc, char* argv[])
{
	int testOpt = 0;
	int key = 0;
	int touchX = 0;
	int touchY = 0;
	
	int opt;
	int option_index;
	const char *short_opts = "t:k:x:y:";
	
	static struct option long_options[] = {
		{"type", required_argument, 0, 't'},
		{"key", required_argument, 0, 'k'},
		{"touchX", required_argument, 0, 'x'},
		{"touchY", required_argument, 0, 'y'},
		{nullptr, 0, nullptr, 0}
	};
	
	while ((opt = getopt_long(argc, argv, short_opts, long_options, &option_index)) != -1) {
		switch(opt) {
			case 't':
				testOpt = atoi(optarg);
				break;
			case 'k':
				key= atoi(optarg);
				break;
			case 'x':
				touchX = atoi(optarg);
				break;
			case 'y':
				touchY = atoi(optarg);
				break;
			default:
				PrintHelp();
				return 0;
		}
	}
	std::cout << "opt: " << testOpt << std::endl;
	std::cout << "key: " << key << std::endl;
	std::cout << "x: " << touchX << std::endl;
	std::cout << "y: " << touchY << std::endl;
	
	if (testOpt == OPT_TOUCH) {
		InjectTouch_api(touchX, touchY);
	} else if (testOpt == OPT_KEY) {
		InjectKey_api(key);
	} else {
		std::cout << "Invalid input params." << std::endl;
		PrintHelp();
	}
	return 0;
}